package com.md.common.utils.qq;

import com.md.common.utils.HttpUtils;
import com.md.common.utils.json.JSONUtil;
import com.md.common.utils.qq.exception.QQApiException;
import com.md.common.utils.qq.model.QQConAccessToken;
import com.md.common.utils.qq.model.QQOpenid;
import com.md.common.utils.qq.model.QQUserInfo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * 功能描述：qq互联api代理
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-9-03 15:13
 * @since JDK 1.8
 */
@Component("qqConnectApiProxy")
public class QQConnectApiProxy {
	private static final Logger LOGGER = LoggerFactory.getLogger(QQConnectApiProxy.class);

//    @Value("${qq.connect.host}")
	private String host = "https://graph.qq.com";
//    @Value("${qq.connect.appId}")
	private String qq_connect_appId;
//    @Value("${qq.connect.secret}")
	private String qq_connect_secret;

    public QQConAccessToken getOauthAccessToken(String code) throws QQApiException {
        String bizDesc = "获取qq互联access token";
        LOGGER.info("{}start", bizDesc);
        QQConAccessToken qqConAccessToken = null;
        StringBuilder sb = new StringBuilder();
        sb.append(host).append("/oauth2.0/token").append(String.format("?grant_type=authorization_code&client_id=%s&client_secret=%s&code=%s&redirect_uri=http://m.dongcmall.com/api/qqcb/oauth2LoginCallBack", qq_connect_appId, qq_connect_secret, code));
        try {
            HttpResponse response = HttpUtils.doGet(sb.toString(), null);
            if (response .getStatusLine().getStatusCode() == 200) {
                String resJson = EntityUtils.toString(response.getEntity(), "UTF-8");
//                JSONObject json = JSONObject.parseObject(resJson);
                if (!resJson.contains("error")) {
                    String[] resParamKvs = resJson.split("&");
                    Map<String, String> reparamKv = new HashMap<String, String>();
                    Stream.of(resParamKvs).forEach(item -> {
                        String[] param = item.split("=");
                        reparamKv.put(param[0], param[1]);
                    });
                    qqConAccessToken = new QQConAccessToken();
                    qqConAccessToken.setAccess_token(reparamKv.get("access_token"));
                    qqConAccessToken.setRefresh_token(reparamKv.get("refresh_token"));
                    qqConAccessToken.setExpires_in(Integer.valueOf(reparamKv.get("expires_in")));
                } else {
                    LOGGER.error("{}失败, result：{}", bizDesc, resJson);
                    throw new QQApiException();
                }
            }
        } catch (Exception e) {
            LOGGER.error("{}异常", bizDesc, e);
            throw new QQApiException();
        }
        LOGGER.info("{}end", bizDesc);
        return qqConAccessToken;
    }

    public QQOpenid getOpenId(String accessToken) throws QQApiException {
        String bizDesc = "获取qq互联openId";
        LOGGER.info("{}start", bizDesc);
        QQOpenid openid = null;
        StringBuilder sb = new StringBuilder();
        sb.append(host).append("/oauth2.0/me").append(String.format("?access_token=%s", accessToken));
        try {
            HttpResponse response = HttpUtils.doGet(sb.toString(), null);
            if (response .getStatusLine().getStatusCode() == 200) {
                String resJson = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (!resJson.contains("error")) {
                    openid = JSONUtil.toBean(resJson.substring(resJson.indexOf("{"), resJson.lastIndexOf("}")+1), QQOpenid.class);
                } else {
                    LOGGER.error("{}失败, result：{}", bizDesc, resJson);
                    throw new QQApiException();
                }
            }
        } catch (Exception e) {
            LOGGER.error("{}异常", bizDesc, e);
            throw new QQApiException();
        }
        LOGGER.info("{}end", bizDesc);
        return openid;
    }

    public QQUserInfo getUserInfo(String accessToken, String openid) throws QQApiException {
        String bizDesc = "获取qq互联用户信息";
        LOGGER.info("{}start", bizDesc);
        QQUserInfo userInfo = null;
        StringBuilder sb = new StringBuilder();
        sb.append(host).append("/user/get_user_info").append(String.format("?access_token=%s&oauth_consumer_key=%s&openid=%s", accessToken, qq_connect_appId, openid));
        try {
            HttpResponse response = HttpUtils.doGet(sb.toString(), null);
            if (response .getStatusLine().getStatusCode() == 200) {
                String resJson = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (!resJson.contains("error")) {
                    userInfo = JSONUtil.toBean(resJson, QQUserInfo.class);
                } else {
                    LOGGER.error("{}失败, result：{}", bizDesc, resJson);
                    throw new QQApiException();
                }
            }
        } catch (Exception e) {
            LOGGER.error("{}异常", bizDesc, e);
            throw new QQApiException();
        }
        LOGGER.info("{}end", bizDesc);
        return userInfo;
    }

    public String getQq_connect_appId() {
        return qq_connect_appId;
    }

    public void setQq_connect_appId(String qq_connect_appId) {
        this.qq_connect_appId = qq_connect_appId;
    }

    public String getQq_connect_secret() {
        return qq_connect_secret;
    }

    public void setQq_connect_secret(String qq_connect_secret) {
        this.qq_connect_secret = qq_connect_secret;
    }
}
